import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { UserService } from "../user/user.service";
import * as md5 from 'md5';
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
    constructor(
        private userService:UserService,
        private jwtService:JwtService,
    ){}
    async login(username,password) {
        const user = await this.userService.findByUsername(username)
        const md5Password = md5(password) as string; 
        if(!user) {
            throw new HttpException('用户不存在',HttpStatus.BAD_REQUEST)
        }
        if(user.active != '1') {
            throw new HttpException('用户未启用',HttpStatus.BAD_REQUEST)
        }
        if(user?.password !== md5Password) {
            throw new HttpException('账号或密码错误',HttpStatus.BAD_REQUEST)
        } else {
            // 生成token
            const payload = { username:user.username,userid:user.id }
            return {
                token:await this.jwtService.signAsync(payload)
            }
        }
    }
}